package com.example.springboot.service;

/**
 * @author yuwl
 * @description
 * @since 2024-05-22 15:36
 */
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.sax.BodyContentHandler;
import org.apache.tika.sax.WriteOutContentHandler;
import org.springframework.stereotype.Service;
import org.xml.sax.SAXException;

import java.io.*;

@Service
public class WordParserService {
    public String parseWord(String filePath) throws IOException, TikaException, SAXException {
        try (InputStream stream = new FileInputStream(filePath)) {
            AutoDetectParser parser = new AutoDetectParser();
            BodyContentHandler handler = new BodyContentHandler();
            Metadata metadata = new Metadata();
            parser.parse(stream, handler, metadata);
            return handler.toString();
        }
    }

    public static String parseWordMix(String filePath) throws IOException, TikaException, SAXException {
        try (InputStream stream = new FileInputStream(filePath)) {
            AutoDetectParser parser = new AutoDetectParser();
            String tmpdir = System.getProperty("java.io.tmpdir");
            String tmpfile = tmpdir + File.separator + "tika_output";
            System.out.println("tmpfile = " + tmpfile);
            File tempFile = File.createTempFile(tmpfile, ".txt");
            try (Writer writer = new BufferedWriter(new FileWriter(tempFile))) {
                WriteOutContentHandler handler = new WriteOutContentHandler(writer);
                Metadata metadata = new Metadata();
                parser.parse(stream, handler, metadata);
                return readTempFileContent(tempFile);
            } finally {
                if (tempFile != null) {
                    tempFile.delete();
                }
            }
        }
    }

    private static String readTempFileContent(File tempFile) throws IOException {
        StringBuilder contentBuilder = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(tempFile))) {
            String line;
            while ((line = reader.readLine()) != null) {
                contentBuilder.append(line).append("\n");
            }
        }
        return contentBuilder.toString();
    }
}



